<template>
  <div class="actionPlan-container" id="actionPlan-dom">
    <div class="section-title" v-if="isAction">
      每天规律治疗方案/恶化时按需使用药物
    </div>
    <XmCardHeader
      v-if="isAction"
      :title="isTreatmentPlan ? '治疗方案' : '行动计划'"
      style="margin-top: 40px"
    >
      <template #select>
        <el-radio-group
          v-model="actionPlanValue"
          :disabled="disabled"
          @change="actionPlanChange"
        >
          <el-radio-button
            v-for="(item, index) in actionVersions"
            :key="index"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio-button>
        </el-radio-group>
      </template>
      <template #right>
        <el-dropdown v-if="isAsthmaDocType">
          <el-button
            v-if="isTreatmentPlan && !isPrinting"
            type="primary"
            :disabled="disabled"
          >
            选择模版
          </el-button>
          <template #dropdown>
            <!-- 已提交不能输入 -->
            <el-dropdown-menu v-if="!disabled">
              <el-dropdown-item @click="addTemplate()">
                西医模版
              </el-dropdown-item>
              <el-dropdown-item v-if="showCNEMR" @click="addCnUse()">
                中医模版
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
          v-else
          type="primary"
          :disabled="disabled"
          @click="addTemplate()"
        >
          选择模版
        </el-button>
      </template>
    </XmCardHeader>
    <div class="regular-treatment">
      <div class="header-title" v-if="showTool(showType, [1, 2, 4, 5])">
        {{ asthmaActionPlanTips.greenTitle }}
      </div>
      <action-table
        v-if="showTool(showType, [1, 4, 5, 8])"
        v-model="actionGreen"
        :is-disabled="disabled"
        tableHeader="规律治疗方案"
        tableColor="#3bba3b"
        @add="showMedical"
        @edit="edit"
        type="actionGreen"
        :ref="setRefs"
      ></action-table>
      <action-table
        v-if="showTool(showType, [2, 5])"
        v-model="usageGreen"
        :is-disabled="disabled"
        tableHeader="如果运动引起哮喘，可在运动前30分钟选择以下药物(如果运动引起哮喘，请及时就医)"
        tableColor="#3bba3b"
        @add="showMedical"
        @edit="edit"
        type="usageGreen"
        :ref="setRefs"
      ></action-table>
    </div>
    <div class="deterioration-treatment">
      <div class="header-title" v-if="showTool(showType, [1, 2, 4, 5])">
        {{ asthmaActionPlanTips.yellowTitle }}
      </div>
      <action-table
        v-if="showTool(showType, [1, 5])"
        v-model="actionYellow"
        :is-disabled="disabled"
        tableHeader="规律治疗方察"
        tableColor="#e7d020"
        @add="showMedical"
        @edit="edit"
        type="actionYellow"
        :ref="setRefs"
      ></action-table>
      <action-table
        v-if="showTool(showType, [2, 4, 5])"
        v-model="usageYellow"
        :is-disabled="
          disabled
            ? disabled || showTool(showType, [4])
            : docType === 0
            ? false
            : showTool(showType, [4])
        "
        :tableHeader="
          showType === 5 ? '恶化时按需使用药物' : '黄区按需使用药物'
        "
        tableColor="#e7d020"
        @add="showMedical"
        @edit="edit"
        type="usageYellow"
        :ref="setRefs"
      ></action-table>
      <div class="header-title" v-if="showTool(showType, [1, 2, 4, 5])">
        {{ asthmaActionPlanTips.redTitle }}
      </div>
      <action-table
        v-if="showTool(showType, [1, 5])"
        v-model="actionRed"
        :is-disabled="disabled"
        tableHeader="规律治疗方察"
        tableColor="#e73f3f"
        @add="showMedical"
        @edit="edit"
        type="actionRed"
        :ref="setRefs"
      ></action-table>
      <action-table
        v-if="showTool(showType, [2, 4, 5])"
        v-model="usageRed"
        :is-disabled="
          disabled
            ? disabled || showTool(showType, [4])
            : docType === 0
            ? false
            : showTool(showType, [4])
        "
        :tableHeader="
          showType === 5 ? '惡化时按需使用药物' : '红区按需使用药物'
        "
        tableColor="#e73f3f"
        @add="showMedical"
        @edit="edit"
        type="usageRed"
        :ref="setRefs"
      ></action-table>
    </div>
    <div class="acute-attack">
      <div v-if="isAction" class="section-title section-margin">
        {{ showType === 5 || 4 ? '急性发作缓解治疗方案：' : '治疗方案' }}
      </div>
      <action-table
        v-if="showTool(showType, [4, 3, 5])"
        v-model="emergencyUse"
        :is-disabled="disabled"
        :tableHeader="showType === 5 ? '急性发作使用药物' : ''"
        @add="showMedical"
        @edit="edit"
        type="emergencyUse"
      ></action-table>
    </div>

    <div class="acute-attack" v-if="isCn">
      <div v-if="isAction" class="section-title section-margin">
        中医治疗方案
      </div>
      <action-table
        v-model="cnUse"
        :is-disabled="disabled"
        tableHeader="中医治疗方案"
        @add="showMedical"
        @edit="edit"
        type="cnUse"
      ></action-table>
    </div>
    <template v-if="isTreatmentPlan">
      <div class="section-title section-margin">其他治疗方案：</div>
      <el-input
        v-if="!isPrinting"
        :disabled="disabled"
        v-model="treatmentPlan"
        maxlength="200"
        placeholder="请输入其他治疗方案"
        show-word-limit
        type="textarea"
      />
      <div v-else class="textarea-content">{{ treatmentPlan }}</div>

      <div class="section-title section-margin">附加治疗方案（生物制剂）：</div>
      <el-input
        v-if="!isPrinting"
        :disabled="disabled"
        v-model="addTreatmentPlan"
        maxlength="200"
        placeholder="请输入附加治疗方案（生物制剂）"
        show-word-limit
        type="textarea"
      />
      <div v-else class="textarea-content">{{ addTreatmentPlan }}</div>

      <div class="section-title section-margin">脱敏治疗：</div>
      <el-input
        v-if="!isPrinting"
        :disabled="disabled"
        v-model="desensitizationTreatment"
        maxlength="200"
        placeholder="请输入脱敏治疗"
        show-word-limit
        type="textarea"
      />
      <div v-else class="textarea-content">{{ desensitizationTreatment }}</div>

      <!-- 复诊时间 -->
      <!-- <EmrReview ref="emrReviewRef" :docType="docType"></EmrReview> -->
    </template>

    <add-medical-record
      ref="addMedicalRef"
      @addMedical="addMedical"
    ></add-medical-record>

    <template-dialog
      ref="templateRef"
      :emrId="emrId"
      :recommendControLevel="controLevel"
      :recommendAcuteSeverity="acuteSeverity"
      @selResult="templateUpdate"
    ></template-dialog>

    <div class="footer-div" v-if="isAction && !isPrinting">
      <debounce-btn
        v-if="!isTreatmentPlan"
        class="footer-button"
        type="primary"
        @debounce="toSave(2)"
        :disabled="sendDisabled"
      >
        提交并发送行动计划
      </debounce-btn>
      <debounce-btn
        v-if="isTreatmentPlan"
        class="footer-button"
        type="primary"
        @debounce="toSave(1)"
        :disabled="disabled"
      >
        保存
      </debounce-btn>
      <el-button
        class="footer-button"
        :disabled="disabled"
        @click="toSave(1, true)"
      >
        存为模板
      </el-button>
      <debounce-btn class="footer-button" type="primary" @debounce="toCanvas()">
        打印
      </debounce-btn>
    </div>
  </div>
</template>
<script>
  import { computed, reactive, ref, toRefs, watch } from 'vue'
  import actionTable from './actionTable'
  import addMedicalRecord from '@/views/reception/components/addMedicalRecord'
  import emr from '@/hooks/emr'
  import DebounceBtn from '@/components/DebounceBtn'
  import { useRoute } from 'vue-router'
  import { useStore } from 'vuex'
  import { save, load, saveASTemplate } from '@/api/modules/actionPlan'
  import common from '@/utils/common'
  import templateDialog from './TemplateDialog'
  import { useActionPlan } from './hooks/useActionPlan'
  import { cloneDeep } from 'lodash-es'
  import {
    useHtml2Canvas,
    downloadBase64ToImg,
  } from '@/hooks/event/useHtml2Canvas'

  import EmrReview from './EmrReview/index.vue'

  // 哮喘
  import asthmaUtils from '../asthma/utils.js'
  export default {
    name: 'actionPlan',
    components: {
      actionTable,
      addMedicalRecord,
      DebounceBtn,
      templateDialog,
      EmrReview,
    },
    props: {
      type: { type: Number, default: 3 },
      isAction: { type: Boolean, default: true },
      vid: Number,
      pid: Number,
      // 病历类型
      // docType: Number,
      // 是否治疗方案
      isTreatmentPlan: { type: Boolean, default: false },
    },
    setup(props) {
      const d = reactive({
        isTemplate: false,
        actionPlanValue: '标准版',
        disabled: false,
        sendDisabled: false,
        docType: null,
        refs: [],
        tableDatas: {
          actionGreen: [],
          actionRed: [],
          actionYellow: [],
          usageGreen: [],
          usageRed: [],
          usageYellow: [],
          emergencyUse: [],
          cnUse: [], // 中医相关的数据
        },
        emrId: null,
        controLevel: null,
        acuteSeverity: null,
        isCn: false,
        // 其他治疗方案文本
        treatmentPlan: null,
        // 附加治疗方案
        addTreatmentPlan: null,
        // 脱敏治疗
        desensitizationTreatment: null,
      })

      // const emrReviewRef = ref(null);

      // eslint-disable-next-line max-len
      // 第一版 showType 决定显示的栏目 1. 有颜色的三区 2. 无颜色的三区 3.急性区 4. 简易版(只有绿区 可添加) 5. 总体模板 1,2,3点都有
      // eslint-disable-next-line max-len
      // 第二版 4,和5变了 showType 决定显示的栏目 1. 有颜色的三区 2. 无颜色的三区 3.急性区 4. 简易版(只有绿区 可添加) 5. 总体模板 1,2,3点都有  4 => 6. 简易版（4的基础上扩展中医） 5 => 7. 总体模版 (5的基础上扩展中医)
      // composition API 设计思路下 似乎不适合拆进hooks?
      /**
       * 1. 有颜色的三区
       * 2. 无颜色的三区
       * 3. 急性区
       * 4. 简易版(只有绿区 可添加)
       * 5. 总体模板 1,2,3点都有
       * 6. 简易版（4的基础上扩展中医） 5
       * 7. 总体模版 (5的基础上扩展中医)
       * 8. 只显示绿区
       */
      const showType = computed(() => {
        if (props.isAction) {
          // 除了中西医，其他都只显示无颜色区
          if (!asthmaUtils.isAsthmaDocType(d.docType)) {
            return 3
          } else {
            return d.actionPlanValue === '简易版' ? 4 : 5
          }
        } else {
          console.log('props.type =' + props.type)
          return props.type
        }
      })
      const isAsthmaDocType = computed(() => {
        return asthmaUtils.isAsthmaDocType(d.docType)
      })
      const route = useRoute()

      // 判断是否为简易版
      const isActionPlanSimple = function () {
        return d.actionPlanValue === '简易版'
      }
      // 帮助判断是否符合显示规则
      const showTool = function (type, presetValues = []) {
        return presetValues.filter((value) => value === type).length > 0
      }
      const addMedicalRef = ref(null)
      const showMedical = function (type) {
        // 标准版的绿区不能批量
        const isNotChangeArea = type === 'usageYellow' || type === 'usageRed'
        addMedicalRef.value.initData(
          type,
          isActionPlanSimple() || isNotChangeArea
        )
      }

      const addMedical = function (data) {
        const {
          red,
          yellow,
          green,
          isColor,
          emergencyUse,
          cnUse,
          type,
          index,
        } = data

        // 判断是否有颜色区域添加的
        const { actionGreen } = d.tableDatas
        if (isColor) {
          if (data.green)
            d.tableDatas.actionGreen = filterUpdate(actionGreen, green, index)
          if (data.red)
            d.tableDatas.actionRed = filterUpdate(
              d.tableDatas.actionRed,
              red,
              index
            )
          if (data.yellow)
            d.tableDatas.actionYellow = filterUpdate(
              d.tableDatas.actionYellow,
              yellow,
              index
            )
        } else {
          if (data.green)
            d.tableDatas.usageGreen = filterUpdate(
              d.tableDatas.usageGreen,
              green,
              index
            )
          if (data.red)
            d.tableDatas.usageRed = filterUpdate(
              d.tableDatas.usageRed,
              red,
              index
            )
          if (data.yellow)
            d.tableDatas.usageYellow = filterUpdate(
              d.tableDatas.usageYellow,
              yellow,
              index
            )
        }
        if (type === 'emergencyUse') {
          d.tableDatas.emergencyUse = filterUpdate(
            d.tableDatas.emergencyUse,
            emergencyUse,
            index
          )
        } else if (type === 'cnUse') {
          d.tableDatas.cnUse = filterUpdate(d.tableDatas.cnUse, cnUse, index)
        }
      }

      // 切换分支
      const actionPlanChange = async function (notClear) {
        // 清理界面上所有数据, 切换默认数据，提示数据丢失
        clear()
        const data = { docType: d.docType, patientId: route.query.id }

        const res = await store.dispatch('emr/getDefaultMedicine', data)
        const { usageGreen, usageRed, usageYellow } = res

        if (d.actionPlanValue === '简易版') {
          d.tableDatas.usageRed = usageRed
          d.tableDatas.usageYellow = usageYellow
        } else if (d.actionPlanValue === '标准版') {
          d.tableDatas.usageGreen = usageGreen
        }
      }

      // 设置table ref
      const setRefs = function (el) {
        d.refs.push(el)
      }

      /**
       * 清空列表数据
       */
      const clear = function (actionPlanValue) {
        const tableDataNames = [
          'actionGreen',
          'actionRed',
          'actionYellow',
          'usageGreen',
          'usageRed',
          'usageYellow',
          'emergencyUse',
          'cnUse',
        ]
        tableDataNames.map((item) => (d.tableDatas[item] = []))
        d.treatmentPlan = null
        d.addTreatmentPlan = null
        d.desensitizationTreatment = null
        if (actionPlanValue) d.actionPlanValue = actionPlanValue
      }

      const {
        initialize,
        initActionPlanData,
        cloneAction,
        templateUpdateData,
        filterUpdate,
        diffUsageGreen,
        isCn,
      } = useActionPlan()

      console.log('isCN =' + isCn)
      // 初始化 界面数据
      const initEmr = function (data, actionPlanValue) {
        if (actionPlanValue) d.actionPlanValue = actionPlanValue
        if (data) {
          const actionData = cloneDeep(data)
          // 赋值过程
          cloneAction(d.tableDatas, actionData)
        }
      }
      const getActionDatas = function () {
        const {
          actionGreen,
          actionRed,
          actionYellow,
          usageGreen,
          usageRed,
          usageYellow,
          emergencyUse,
          cnUse,
        } = d.tableDatas
        let tmpUsageGreen = usageGreen
        if (
          asthmaUtils.isAsthmaDocType(d.docType) &&
          d.actionPlanValue === '标准版'
        ) {
          tmpUsageGreen = usageGreen.filter((item) => item.backSave === true)
        }
        return {
          actionGreen,
          actionRed,
          actionYellow,
          usageGreen: tmpUsageGreen,
          usageRed,
          usageYellow,
          emergencyUse,
          cnUse,
        }
      }

      const edit = function (config) {
        console.log('config =' + JSON.stringify(config))
        const { data, index, type } = config
        // 标准版
        const isNotChangeMedines =
          d.actionPlanValue === '标准版' && type === 'usageGreen'
        // 简易版 另外两个区不能加药
        const notChangeAera =
          d.actionPlanValue === '简易版' && type === 'actionGreen'
        addMedicalRef.value.initData(type, true, isNotChangeMedines, {
          ...data,
          index,
        })
      }

      const store = useStore()
      const toSave = async function (status, isSaveTemplate) {
        // emrReviewRef.value.saveReview();
        // return;

        if (!route.query.emrId) {
          common.XmMessage(3, '需要先提交病历')
          return
        }
        // const actionDatas = getActionDatas()
        await common.syncAlert(
          status === 2
            ? '该行动计划将发送给患者，【治疗方案】和【行动计划】将不能修改'
            : null
        )
        const data = {
          actionPlanType: d.actionPlanValue,
          content: getActionDatas(),
          medicalRecordId: route.query.emrId,
          patientId: props.pid,
          status,
          treatmentPlan: d.treatmentPlan,
          addTreatmentPlan: d.addTreatmentPlan,
          desensitizationTreatment: d.desensitizationTreatment,
        }
        common.XmLoading(true)
        await save(data)
          .then((res) => {
            common.XmLoading()
            if (status === 2) {
              d.disabled = true
              d.sendDisabled = true
            }
            if (isSaveTemplate) {
              saveTemplate()
              return
            }
            common.XmMessage(0, res.message)
            store.dispatch('patient/loadEmrStatus', {
              medicalRecordId: route.query.emrId,
              patientId: route.query.id,
            })
          })
          .catch(() => {
            common.XmLoading()
          })
      }

      const toLoad = async function (emrId) {
        // 目前只有简易版才能加载出数据
        const res = await load({
          medicalRecordId: emrId,
          actionPlanType: '标准版',
        })

        const data = {
          docType: res.data.docType,
          patientId: route.query.id,
        }
        const { usageGreen, usageRed, usageYellow } = await store.dispatch(
          'emr/getDefaultMedicine',
          data
        )
        if (res.data) {
          console.log('res.data = ' + JSON.stringify(res.data))

          d.docType = res.data.docType
          if (res.data.dto && res.data.dto.status === 2) {
            d.disabled = true
            d.sendDisabled = true
          }
          if (!props.isTreatmentPlan) {
            d.disabled = true
          }
          const {
            content,
            recommendControLevel,
            actionPlanType,
            recommendAcuteSeverity,
            treatmentPlan,
            addTreatmentPlan,
            desensitizationTreatment,
            isCn,
          } = initActionPlanData(res.data)
          // 缓存推荐诊断
          d.controLevel = recommendControLevel
          d.acuteSeverity = recommendAcuteSeverity
          d.actionPlanValue = actionPlanType
          // 其他治疗方案文本
          d.treatmentPlan = treatmentPlan
          // 附加治疗方案
          d.addTreatmentPlan = addTreatmentPlan
          // 脱敏治疗
          d.desensitizationTreatment = desensitizationTreatment
          // 赋值过程
          cloneAction(d.tableDatas, content)
          // 是否中医
          d.isCn = isCn
          if (d.actionPlanValue === '简易版') {
            d.tableDatas.usageRed = diffUsageGreen(
              usageRed,
              d.tableDatas.usageRed
            )
            d.tableDatas.usageYellow = diffUsageGreen(
              usageYellow,
              d.tableDatas.usageYellow
            )
          } else {
            if (!actionPlanType) d.actionPlanValue = '标准版'
            d.tableDatas.usageGreen = diffUsageGreen(
              usageGreen,
              d.tableDatas.usageGreen
            )
          }

          // 使用切换去初始化
          // actionPlanChange(true)
        }
      }

      const templateRef = ref(null)
      const selectTemplatePlan = function (templateType) {
        console.log('诊断时候会给治疗方案 & templateType =' + templateType)
        // 诊断时候会给治疗方案
        /**
         * docType
         * 中西医病例(4) docType=4 actionPlanValue='简易版' => showType=2
         * 中西医病例(4) docType=3 actionPlanValue='标准版' => showType=1
         * 其他病例 + 点击中医按钮 docType => showType=3
         * templateType 目前只用到了中医3
         *  西医 1 鼻炎 2 中医 3
         */
        let showType = 3
        if (
          asthmaUtils.isAsthmaDocType(d.docType) &&
          d.actionPlanValue === '简易版' &&
          templateType !== 3
        ) {
          showType = 2
        } else if (
          asthmaUtils.isAsthmaDocType(d.docType) &&
          d.actionPlanValue === '标准版' &&
          templateType !== 3
        ) {
          showType = 1
        }
        console.log('showType =' + showType)
        templateRef.value.initData(d.actionPlanValue, showType, templateType)
      }

      // 模版数据更新 所有数据需要走这里，分配uuid。
      const templateUpdate = function (values) {
        const templateData = templateUpdateData(values, d.actionPlanValue)
        console.log('templateData =' + JSON.stringify(templateData))
        cloneAction(d.tableDatas, templateData)
      }

      const saveTemplate = async function () {
        // d.emrId
        common.XmLoading()
        await saveASTemplate({
          medicalRecordId: route.query.emrId,
          actionPlanValue: d.actionPlanValue,
        })
          .then(() => {
            common.XmLoading(false)
            common.XmMessage(0, '保存成功')
          })
          .catch(() => {
            common.XmLoading(false)
          })
      }

      const addCnUse = function () {
        // 注释看方法里
        selectTemplatePlan(3)
      }
      const addTemplate = function () {
        if (asthmaUtils.isAsthmaDocType(d.docType)) {
          selectTemplatePlan(1)
        } else {
          selectTemplatePlan(d.docType)
        }
      }
      watch(
        () => route.query.emrId,
        async (emrId) => {
          console.log('emrId =' + emrId)
          if (emrId) {
            console.log(' is change =' + emrId)
            d.emrId = emrId
            toLoad(emrId)
            // emrRef.value.clear()
          } else {
            // emrRef.value.clear()
          }
        },
        { immediate: true }
      )

      const { htmlToImg, downloadBase64ToImg } = useHtml2Canvas()
      // 在打印中
      const isPrinting = ref(false)
      const toCanvas = function () {
        const tmpDisabled = d.disabled
        d.disabled = true
        isPrinting.value = true
        htmlToImg('actionPlan-dom', (str) => {
          isPrinting.value = false
          d.disabled = tmpDisabled
          const name = store.getters.patientInfo.name + '的治疗方案'
          downloadBase64ToImg(str, name)
        })
      }

      const showCNEMR = computed(() => {
        return store.getters.showCNEMR
      })
      return {
        isAsthmaDocType,
        // emrReviewRef,
        ...toRefs(d),
        ...toRefs(d.tableDatas),
        addMedical,
        showMedical,
        actionPlanChange,
        addMedicalRef,
        showType,
        showTool,
        getActionDatas,
        edit,
        ...emr(),
        toSave,
        setRefs,
        clear,
        initEmr,
        selectTemplatePlan,
        templateRef,
        templateUpdate,
        saveTemplate,
        addCnUse,
        addTemplate,
        toCanvas,
        isPrinting,
        showCNEMR,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .actionPlan-container {
    .header-title {
      font-size: 14px;
      margin-top: 40px;
    }

    .section-title {
      font-size: 18px;
      margin: 6px;
      position: relative;

      &:before {
        content: '';
        position: absolute;
        left: -6px;
        // top: 12px;
        width: 2px;
        height: 100%;
        border-left: 4px solid var(--el-color-primary);
        box-sizing: border-box;
        border-radius: 2px;
      }
    }

    .section-margin {
      margin-top: 20px;
      margin-bottom: 10px;
    }

    .textarea-content {
      min-height: 80px;
      border: 0;
      margin: 0;
      // background-color: #f2f2f2;
      padding: 6px;
      border: 1px;
      background-color: var(--el-disabled-bg-color);
      border-color: var(--el-disabled-border-color);
      color: var(--el-disabled-text-color);
      cursor: not-allowed;
    }

    .footer-div {
      margin-top: 10px;

      .el-button {
        float: right;
        margin-right: 12px;
        margin-left: 0px;
      }
    }
  }
</style>
